package com.imyours.webservice.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;

import com.imyours.model.department.DepartmentEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.webservice.service.Context;
import com.imyours.webservice.service.ContextService;
import com.imyours.webservice.services.annotation.Service;

/**
 * 获取公司组织结构
 * 
 * @author SLevenc
 * 
 */
@Service(name = "getDepartment")
public class GetDepartment extends ContextService {

	public GetDepartment(Context context) {
		super(context);
	}

	public void execute() {
		UserEntity user = getUserEntity();
		if (user != null) {
			Session se = HibernateUtil.getSessionFactory().openSession();
			DepartmentEntity root = (DepartmentEntity) se.get(DepartmentEntity.class, -1L);
			context.setResult(buildTree(root));
			context.success();
		}
	}

	private Map buildTree(DepartmentEntity depart) {
		Map me = new HashMap();
		me.put("name", depart.getName());
		me.put("id", depart.getId());
		Session se = HibernateUtil.getSessionFactory().openSession();
		List<Map<String, String>> userList = new ArrayList<Map<String, String>>();
		if (depart.getUsers() != null) {
			for (UserEntity ue : depart.getUsers()) {
				Map<String, String> userMap = new HashMap<String, String>();
				userMap.put("id", "" + ue.getId());
				userMap.put("nickName", ue.getNickname());
				userList.add(userMap);
			}
		}
		me.put("users", userList);

		List<DepartmentEntity> dList = se.createQuery("from DepartmentEntity where parentDepartment=?").setEntity(0, depart)
				.list();
		List<Map<String, String>> childList = new ArrayList<Map<String, String>>();
		Map<String, String> cmap = null;
		if (dList.size() > 0) {
			for (DepartmentEntity de : dList) {
				childList.add(buildTree(de));
			}
		}
		me.put("child", childList);
		return me;
	}
}
